package com.aircms.interceptor;

import com.aircms.common.Common;
import com.aircms.common.ServerResponse;
import com.aircms.pojo.vo.RolePermissionVo;
import com.aircms.service.IRolePermissionService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author air
 * @create 2018-06-27 下午2:38
 */
public class InterceptorAuth implements HandlerInterceptor {

    @Autowired
    private IRolePermissionService iRolePermissionService;

    private static final Logger logger=LoggerFactory.getLogger(InterceptorAdmin.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(Common.getUserId()==1){  // 超级管理员，不验证权限
            return true;
        }
        String string= Common.getUserRoleId();
        String[] roleIds=string.split(",");

        if(!checkPermission(request,getPermissionByRoleIds(roleIds))){// 权限不够
            ServerResponse serverResponse=ServerResponse.response("",-110);  // 您没有权限，请联系管理员
            // 对象转json
            ObjectMapper objectMapper=new ObjectMapper();
            response.getWriter().append(objectMapper.writeValueAsString(serverResponse));
            return  false;
        }
        return  true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


    /**
     * 获取角色权限
     * @param roleIds
     * @return
     */
    private List<RolePermissionVo> getPermissionByRoleIds(String [] roleIds){
        ServerResponse serverResponse=iRolePermissionService.getRoleRouterPermissionIds(roleIds);
        List<RolePermissionVo> rolePermissions= (List<RolePermissionVo>) serverResponse.getData();
        return  rolePermissions;
    }

    /**
     * 权限检查
     * @return
     */
    private Boolean checkPermission(HttpServletRequest request, List<RolePermissionVo> list){
        String[] requestLength=request.getServletPath().split("/");  // 分割路由

        for(RolePermissionVo item:list){
            String[] lengthList=item.getUrl().split("/");
            if(lengthList.length!=requestLength.length||item.getMethod().indexOf(request.getMethod())<0){// 验证路由长度和请求方式
                continue;
            }

            int mark=0;        // 设置标记
            for (int i = 0; i <requestLength.length ; i++) {
                if(lengthList[i].indexOf("{")<0){// 忽略理由中的参数（参数可变）
                    if(!requestLength[i].equals(lengthList[i])){// 如果不匹配直接跳出for循环，不再往下验证
                        mark++;
                        break;
                    }
                }
            }
            if(mark==0){// 路由通过
                return true;
            }
        }
        return false;
    }


}
